<?php
/**
 * @file
 */

/**
 * Menu callback: management operators
 */
function chatroom_livesupport_operators_form($form, &$form_state) {
  $form = chatroom_livesupport_operators_operations($form, $form_state);
  $header = array(
    'username' => array('data' => t('Username'), 'field' => 'u.name'),
    'status' => array('data' => t('Status')),
    'member_for' => array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    'access' => array('data' => t('Last access'), 'field' => 'u.access')
  );

  $query = db_select('chatroom_operator', 'o');

  $count_query = clone $query;
  $count_query->addExpression('COUNT(o.uid)');

  $query->innerJoin('users', 'u', 'u.uid = o.uid');
  $query->fields('o', array('oid', 'timestamp'));

  $query->condition('u.uid', 0, '<>');
  if (!empty($_SESSION['chatroom_livesupport_operators_filter']['name'])) {
    $query->condition('u.name', $_SESSION['chatroom_livesupport_operators_filter']['name'], 'LIKE');
  }

  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('u')
    ->limit(20)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

  $destination = drupal_get_destination();
  $options = array();
  foreach ($result as $account) {
    $options[$account->oid] = array(
      'username' => theme('username', array('account' => $account)),
      'status' =>  chatroom_livesupport_is_online_user($account->uid) ? t('Online') : t('Offline'),
      'member_for' => format_interval(REQUEST_TIME - $account->created),
      'access' =>  $account->access ? t('@time ago', array('@time' => format_interval(REQUEST_TIME - $account->access))) : t('never'),
    );
  }

  $form['operators'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No operator available.'),
  );

  $form['pager'] = array('#markup' => theme('pager'));

  return $form;
}

/**
 * Function helper chatroom_livesupport_operators_page()
 */
function chatroom_livesupport_operators_operations($form, &$form_state) {
  $form['operations'] = array(
    '#type' => 'fieldset',
    '#title' => t('Operations'),
    '#collapsible' => TRUE,
    '#collapsed' =>TRUE
  );
  $form['operations']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 20,
    '#autocomplete_path' => 'user/autocomplete',
    '#default_value' => !empty($_SESSION['chatroom_livesupport_operators_filter']['name']) ? $_SESSION['chatroom_livesupport_operators_filter']['name'] : '',
    '#description' => t('Enter username')
  );
  $form['operations']['actions'] = array(
    '#type' => 'select',
    '#title' => t('Operations'),
    '#options' => array(
      '' => t('Choose operation'),
      'add' => t('Add operator'),
      'remove' => t('Remove operator(s)'),
      'filter' => t('Find this operator')
    )
  );
  $form['operations']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('chatroom_livesupport_operators_form_submit')
  );
  return $form;
}

/**
 * Submit callback: chatroom_livesupport_operators_operations_form
 */
function chatroom_livesupport_operators_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  switch ($values['actions']) {
    case 'add':
      // Add operator
      if (!empty($values['name'])) {
        $account = user_load_by_name($values['name']);
        if ($account) {
          $operator = chatroom_livesupport_save_operator($account);
          if ($operator->oid) {
            drupal_set_message(t('An operator has been added successful'));
          }
        }
      }
      else {
        drupal_set_message(t('Don\'t add operator. Username is invalid or User has been exists operator'));
      }
      break;
    case 'remove':
      // Remove one or some operator
      $operators = $values['operators'];
      if ($operators) {
        db_delete('chatroom_operator')->condition('oid', array_values($operators), 'IN')->execute();
        drupal_set_message(t('Some operators have been successful removed'));
      }
      break;
    case 'filter':
      // Filter operator
      if (!empty($values['name'])) {
        $account = user_load_by_name($values['name']);
        if ($account) {
          $_SESSION['chatroom_livesupport_operators_filter'] = array('name' => $values['name']);
        }
      }
      break;
    default:
      $_SESSION['chatroom_livesupport_operators_filter'] = array('name' => '');
  }
}